require "pathname"
require "cgi"

# load the openid library
begin
  require "rubygems"
  require_gem "ruby-openid", ">= 1.0.2"
rescue LoadError
  require "openid"
end

class AuthController < ApplicationController
  layout  'scaffold'
  
  # process the login request, disover the openid server, and
  # then redirect.
  def login
    #openid_url = params[:openid_url]
    openid_url = "http://api.openmaru.com/auth_keys/springnote?openid=#{params[:openid_url]}"
    @session = session
    if request.post?
      request = consumer.begin(openid_url)

      case request.status
      when OpenID::SUCCESS
        return_to = url_for(:action=> 'complete')
        trust_root = url_for(:controller=>'')

        url = request.redirect_url(trust_root, return_to)
        redirect_to(url)
        return

      when OpenID::FAILURE
        escaped_url = CGI::escape(openid_url)
        flash[:notice] = "Could not find OpenID server for #{escaped_url}"
        
      else
        flash[:notice] = "An unknown error occured."

      end      
    end    

  end

  # handle the openid server response
  def complete
    @session = session
    response = consumer.complete(params)
    
    case response.status
    when OpenID::SUCCESS

      session[:id] = params['openid.identity']
      user_key = response.extension_response('sreg')['postcode']
      flash[:notice] = "Logged in as #{session[:id]}"
      session[:key] = user_key  
      cookies[:openid] = session[:id] 
      
      runners = CONFIG['runners']
      registered = false
      runners.each do |runner|
        # TODO maybe normalized?
        if runner['runner']['id'] == session[:id]
          runner['runner']['key'] = user_key
          registered = true
        end
      end
      
      unless registered
        runners << {'runner' => {'id' => session[:id], 'key' => user_key}}
        File.open("#{RAILS_ROOT}/config/springnote.yml", 'w') do |out|
          YAML.dump(CONFIG, out)
        end
      end
      if session[:location] 
        redirect_to session[:location]
        session[:location] = nil
      else
        redirect_to :controller => "pages", :action => "index"
      end
      return

    when OpenID::FAILURE
      if response.identity_url
        flash[:notice] = "Verification of #{CGI::escape(response.identity_url)} failed."

      else
        flash[:notice] = 'Verification failed.'
      end

    when OpenID::CANCEL
      flash[:notice] = 'Verification cancelled.'

    else
      flash[:notice] = 'Unknown response from OpenID server.'
    end
  
    redirect_to :action => 'login'
  end
  
  def logout
    session[:key] = nil
    session[:runner] = nil
  end
    
  def welcome
  end

  private

  # Get the OpenID::Consumer object.
  def consumer
    # create the OpenID store for storing associations and nonces,
    # putting it in your app's db directory
    store_dir = Pathname.new(RAILS_ROOT).join('db').join('openid-store')
    store = OpenID::FilesystemStore.new(store_dir)

    return OpenID::Consumer.new(@session, store)
  end

  # get the logged in user object
  def find_user
    return nil if session[:user_id].nil?
    User.find(session[:user_id])
  end
  
end
